<script setup>
// import { List } from '@element-plus/icons-vue/dist/types';
import { reactive, ref, defineOptions, computed,onMounted } from "vue";
import router from "../../router";
import { addRoleApi, getRoleDetail } from "../../api/role";
import { useRouter,useRoute } from "vue-router";
defineOptions({
  name: "add-role",
});
const formSize = ref("default");
const ruleForm = reactive({
  name: "",
  desc: "",
});

const route = useRoute()
// console.log(route.query,'fdfdf')
const isEdit = !!route.query.id
const checkAll = ref();
const isIndeterminate = ref(false);
const checkedMenus = ref([]);
const setCheckedStatus = (item) => { 
  item.isChecked = false
  if (item.children && item.children.length) { 
    item.children = item.children.map(child => setCheckedStatus(child))
  }
  return item
}

onMounted(async () => { 
  if (isEdit) { 
    const data =await getRoleDetail(route.query.id)
    const { menus, name, desc } = data.data.data
    checkedMenus.value = menus
    handlecheckedMenusChange(menus)
    ruleForm.name = name || ''
    ruleForm.desc = desc || ''
  }
})
const menus = ref(router.options.routes[0].children.map(item => setCheckedStatus(item)));
console.log(menus,'menus')

//拿到所有路由的名称
const flatten = (arr) => {
  return arr.reduce(function (pre, cur) {
    console.log(cur,'currr')
    return pre.concat(cur).concat(
      Array.isArray(cur.children) && cur.children.length ? flatten(cur.children) : []
    );
  }, []);
};
//全部路由的标识
const allMenuKeys = computed(() => {
  return flatten(menus.value).map((item) => item.name);
});
//全选
const handleCheckAllChange = (val) => {
  checkedMenus.value = val ? allMenuKeys.value : [];
  isIndeterminate.value = false;
};
//判断需不需要半选或全选
const handlecheckedMenusChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === allMenuKeys.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < allMenuKeys.value.length;
};

//保存按钮
function saveAction() {
  const requestData = {
    ...ruleForm,
    menus: checkedMenus.value,
  }
  addRoleApi(requestData).then(res => {
    console.log(res,11111)
  })
  router.push({ name: "role" });
}
//取消按钮
function cancelAction() {
  router.push({ name: "role" });
}

const hasSomeChildSelected = (menu) => { 
  return menu.children && menu.children.some(item => item.isChecked) && !menu.children.every(item => item.isChecked)
}
//子级关联全选半选的权限
const setParentValue = (val, childMenu,menu) => { 
  childMenu.isChecked = val
  const menusKey = menu.children.map(item => item.name)
  
  menu.isChecked = !!checkedMenus.value.find(item => menusKey.includes(item))
  if(menu.isChecked) {
    !checkedMenus.value.includes(menu.name) &&  checkedMenus.value.push(menu.name)
  } else {
    checkedMenus.value = checkedMenus.value.filter(name => name !== menu.name)
  }
}

//全选子级
const setChildMenu = (val, menu) => { 
  menu.isChecked = val
  if (val) { 
    !checkedMenus.value.includes(menu.name) &&  checkedMenus.value.push(menu.name)
  } else {
    checkedMenus.value = checkedMenus.value.filter(name => name !== menu.name)
  }
  if (menu.children && menu.children.length) { 
    menu.children.forEach(item => {
      item.isChecked = val
      if (val && !checkedMenus.value.includes(item.name)) {
        // if (!hasSomeChildSelected(menu)) { 
          !checkedMenus.value.includes(item.name) &&  checkedMenus.value.push(item.name)
        // }
        
      } else { 
        checkedMenus.value = checkedMenus.value.filter(name => name !== item.name)
      }
    })
    }
}
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-form"
    :size="formSize"
    status-icon
  >
    <el-form-item label="角色名:" prop="name">
      <el-input v-model="ruleForm.name" size="small" style="width: 215px" />
    </el-form-item>
    <el-form-item label="角色说明:" prop="desc">
      <el-input v-model="ruleForm.desc" type="textarea" style="width: 300px" />
    </el-form-item>
  </el-form>
  <el-checkbox
    v-model="checkAll"
    :indeterminate="isIndeterminate"
    @change="handleCheckAllChange"
    >全选</el-checkbox
  >

  <div class="first-menu pl30" v-for="menu in menus" :key="menu.path">
    <el-checkbox-group
      v-model="checkedMenus"
      @change="handlecheckedMenusChange"
    >
      <el-checkbox @change="(val) => setChildMenu(val,menu)" :indeterminate="menu.children && menu.children.length && hasSomeChildSelected(menu)" :checked="menu.isChecked" :label="menu.name">{{ $t(menu.meta.title) }} </el-checkbox>
    </el-checkbox-group>

    <div class="second-menus box">
      <el-checkbox-group
        v-model="checkedMenus"
        @change="handlecheckedMenusChange"
      >
        <el-checkbox
          v-for="childMenu in menu.children"
          :key="childMenu.path"
          :label="childMenu.name"
          :checked="childMenu.isChecked"
          @change="(val)=>setParentValue(val,childMenu,menu)"
          >{{ $t(childMenu.meta.title) }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </div>
  <div>
    <el-button type="primary" @click="saveAction">保存</el-button>
    <el-button @click="cancelAction">取消</el-button>
  </div>
</template>

<style scoped lang="scss">
.box {
  padding: 0 30px;
}
</style>
